use tokio::time;

use crate::{components, dao};
use crate::models::models::components::v2ray::info::ComponentV2rayState;
use crate::models::models::components::v2ray::server::ComponentV2rayServer;
use crate::runtime::error::MagicBoxError;
use crate::runtime::response::{Code, MagicBoxResponse};
use crate::runtime::result::MagicBoxResult;

#[tauri::command(rename_all = "snake_case")]
pub(crate) async fn invoke_component_v2ray_save_server(server: ComponentV2rayServer) -> MagicBoxResult<MagicBoxResponse<()>> {
    if "" == server.uuid || "" == server.tag || "" == server.address || "" == server.user_id {
        return Err(MagicBoxError::new(Code::ParameterError, "服务器配置无效，请检查配置参数是否完整"));
    }

    // 重置选择状态
    if server.used {
        dao::components::v2ray::server::reset_server_used()?;
    }

    dao::components::v2ray::server::save_server_config(server.clone(), false)?;

    // 重启服务
    if server.used && ComponentV2rayState::Running == components::v2ray::manager::manager().state()? {
        components::v2ray::manager::manager().stop()?;

        time::sleep(time::Duration::from_millis(1000)).await;
        components::v2ray::manager::manager().start()?;
    }

    Ok(MagicBoxResponse::new_empty_success())
}